<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>RTMP Mediapipe Demos</title>
  </head>
  <body>
    <link href="./main.css" rel="stylesheet" type="text/css"/>
    <div id="root">
      <div class="flex-col">
        <div><canvas id='canvas' width="640" height="480"></canvas></div>
        <div>
          <label for="wsUrl">Websocket地址:</label>
          <input id="wsUrl" type="text" value="ws://192.168.31.89:5500"/>
          <input type="button" id="btnConn" value="连接" />
          <input type="button" id="btnClose" disabled value="断开" />
        </div>
      </div>
      
      <div class="flex-col">
        <video width="640" height="480" autoPlay id="videoElement" crossOrigin='anonymous' controls></video>
        <div>
          <label for="flvUrl">视频流地址:</label>
          <input id="flvUrl" type="text" value="http://192.168.31.89:8080/live/webcam.flv"/>
          <input type="button" id="btnPlay" value="播放视频流" />
        </div>
      </div>
    </div>
    <script src="flv.min.js"></script>
    <script type="module">
      import * as FlvJs from './flv.min.js'; 

      const flvUrl = document.getElementById('flvUrl');
      const wsUrl = document.getElementById('wsUrl');
      const btnPlay = document.getElementById('btnPlay');
      const btnConn = document.getElementById('btnConn');
      const btnClose = document.getElementById('btnClose');
      const canvas = document.querySelector('canvas');

      var imageWidth = 640;
      var imageHeight = 480;
      const colorMap = ['red', 'green', 'blue', 'yellow'];

      let flvPlayer;
      let websocket;


      btnPlay.addEventListener('click', playFlv, false);
      btnConn.addEventListener('click', connect, false);
      btnClose.addEventListener('click', close, false);

      clearCanvas();
      drawPoint(imageWidth/2, imageHeight/2);

      function playFlv() {
        if (flvjs.isSupported()){
          
          if( flvPlayer ){
            console.log(flvPlayer)
            flvPlayer.destroy();
          }

          var videoElement = document.querySelector('video');
          if( !videoElement ) return;

          flvPlayer = flvjs.createPlayer({
              type: 'flv',
              url: flvUrl.value
          });
          const errorLog = document.getElementById('error');

          flvPlayer.attachMediaElement(videoElement);
          flvPlayer.load();
          flvPlayer.play();

        }
      }
      
      function connect() {
        
        if( websocket && websocket.readyState === WebSocket.OPEN ){
          return;
        }

        const url = wsUrl.value;
        console.log('connect to ', url)
        websocket = new WebSocket(url);

        // Connection opened
        websocket.addEventListener('open', function (event) {
          alert('连接成功!');
          btnConn.disabled = true;
          btnClose.disabled = false;
        });

        // Listen for messages
        websocket.addEventListener('message', function (event) {
            // console.log('Message from server ', event.data);
            drawLandmarks(JSON.parse(event.data));
        });

        // Listen for error
        websocket.addEventListener('error', function (event) {
          alert('连接失败!');
          btnConn.disabled = true;
          btnClose.disabled = false;
        });

        // Listen for close
        websocket.addEventListener('close', function (event) {
          alert('连接断开!');
        });
      }

      function close(){
        if( websocket && websocket.readyState === WebSocket.OPEN) {
          websocket.close();
          btnConn.disabled = false;
          btnClose.disabled = true;
        }
      }

      function clearCanvas( color = 'gray') {
        var ctx=canvas.getContext("2d");
        if( ctx ) {
          ctx.clearRect( 0, 0, imageWidth, imageHeight );
          if( color ){
            ctx.fillStyle = color;
            ctx.fillRect( 0, 0, imageWidth, imageHeight );
          }
        }
      }

      function drawPoint( x, y, color='red', size=5 ) {
        var ctx=canvas.getContext("2d");
        if( ctx ) {
          ctx.beginPath();
          ctx.fillStyle = color;
          ctx.arc( x, y, size, 0, Math.PI*2 );
          ctx.fill();
        }
      }

      function drawLandmarks( landmarks ) {
        const hands = landmarks.hands;
        const face_mesh = landmarks.face_mesh;
        clearCanvas();
        for( var i = 0, il = hands.length; i < il; i++ ) {
          const hands_landmarks = hands[i];
          for( var j = 0, jl = hands_landmarks.length; j < jl; j++ ) {
            const landmark = hands_landmarks[j];
            const x = ( 1 - landmark[0] ) * imageWidth;
            const y = landmark[1] * imageHeight;
            drawPoint( x, y, colorMap[i]);
          }
        }

        for( var i = 0, il = face_mesh.length; i < il; i++ ) {
          const face_mesh_landmarks = face_mesh[i];
          for( var j = 0, jl = face_mesh_landmarks.length; j < jl; j++ ) {
            const landmark = face_mesh_landmarks[j];
            const x = ( 1 - landmark[0] ) * imageWidth;
            const y = landmark[1] * imageHeight;
            drawPoint( x, y, colorMap[i]);
          }
        }
        
      }

    </script>

  </body>
</html>
